package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.question.domain.LastRecord;
import com.wuwei.elearning.question.mapper.LastRecordMapper;
import com.wuwei.elearning.question.service.LastRecordService;
import com.wuwei.elearning.setting.domain.User;
import com.wuwei.elearning.setting.mapper.UserMapper;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户上一次做题记录，该表用于记录用户上一次练习时练习的是哪一个科目，该表方便用户下次点击时不需要重新选择科目 前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-03-28
 */
@RestController
@CrossOrigin
@RequestMapping("/elearning/lastRecord")
public class LastRecordController {


    @Resource
    private LastRecordMapper lastRecordMapper;

    @Resource
    private LastRecordService lastRecordService;

    /**
     * 当用户选择了某一个课程章节后，如果表中没有数据，则添加，如果有，则修改
     * @return
     */
    @PostMapping("addOrUpdate")
    public Result<String> addOrUpdate(@RequestBody LastRecord record, HttpServletRequest request){
        Long selectedId = record.getSelectedId();
        String chapterName = record.getChatperName();
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        lastRecordService.addOrUpdate(record,account,selectedId,chapterName);
        return Result.ok("用户刷题章节记录更新成功!");
    }

    @GetMapping("getLastRecord")
    public Result<LastRecord> getLastRecord(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);


        LambdaQueryWrapper<LastRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LastRecord::getUserAccount,account);

        LastRecord lastRecord = lastRecordMapper.selectOne(queryWrapper);

        if (lastRecord==null) {//如果为空，则表示该用户第一次进入该系统，查不到之前的记录
            return Result.ok(null);
        } else {
            //为了对之前的数据兼容，如果有之前的数据进来，这时候会将其减10000
            if (lastRecord.getSelectedId()>10000) {
                lastRecord.setSelectedId(lastRecord.getSelectedId()-10000);
            }
            return Result.ok(lastRecord);
        }
    }

}

